<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"
      :default-params="{ actualEndTime: [], actualBeginTime: [], payStatus:defaultStatus }"  @submit="handleSeachTable">
      <t-col :span="3">
        <t-form-item label="客户名称" name="customerName">
          <t-input v-model:value="params.customerName" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客服" name="saleId">
          <t-cascader
            v-model:value="params.saleId"
            :options="saleTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="设计师" name="designerId">
          <t-cascader
            v-model:value="params.designerId"
            :options="designerTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      
      <t-col :span="3">
        <t-form-item label="工程部经理" name="engineeringManagerId">
          <t-cascader
            v-model:value="params.engineeringManagerId"
            :options="engineeringManagerTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="收款期数" name="payNumber">
          <t-input v-model:value="params.payNumber" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="支付状态" name="payStatus">
          <t-select v-model:value="params.payStatus" :options="dictionaryStore.get('pay_status')" clearable
            filterable placeholder="" />
        </t-form-item>
      </t-col>
    
     
  
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="payContractZhengCRUD.page"
      column-controller-key="FinancePayList"
      :foot-data="footData"
      :on-before-set-data="handleTableSetData"
      >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-radio-group v-model="defaultCompany" theme="button" @change="handleCompanyChange">
            <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
          </t-radio-group>
        </div>
      </template>


      <template #engineeringStage="{ row }">
        <span v-if="row.isDesigner=='1'">设计订单</span>
        <span v-if="row.isDesigner=='0'"> {{ dictionaryStore.analysis('engineering_stage', row.engineeringStage) }}</span>
      </template>
      <template #engineeringStatus="{ row }">
        <span v-if="row.isDesigner=='1'">设计订单</span>
        <span v-if="row.isDesigner=='0'"> {{ dictionaryStore.analysis('engineering_status', row.engineeringStatus) }}</span>
      </template>
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #designerId="{ row }">
        {{ userStore.getUserNameById(row.designerId) }}
      </template>
      <template #productDesignerId="{ row }">
        {{ userStore.getUserNameById(row.productDesignerId) }}
      </template>
      <template #engineeringManagerId="{ row }">
        {{ userStore.getUserNameById(row.engineeringManagerId) }}
      </template>
      <template #supervisionId="{ row }">
        {{ userStore.getUserNameById(row.supervisionId) }}
      </template>
      <template #propertyName="{ row }">
        {{propertyInfoList.find((item) => item.id === row.propertyName)?.name}}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #pressForMoneyStage="{ row }">
        {{ dictionaryStore.analysis('pay_stage', row.pressForMoneyStage) }}
      </template>
      <template #payStatus="{ row }">
        {{ dictionaryStore.analysis('pay_status', row.payStatus) }}
      </template>
      <template #engineeringCostDiff="{ row }">
        <engineering-cost-diff-dialog 
          :collection-id="row.id"
          :order-id="row.orderId"
          :payment-stage="row.paymentStage"
          :engineering-cost-diff="row.engineeringCostDiff"
          @refresh="handleRefreshTable"
        /> 
      </template>
      <template #amountReceived="{ row }">
        <amount-received-dialog
          :collection-id="row.id"
          :order-id="row.orderId"
          :payment-stage="row.paymentStage"
          :amount-received="row.amountReceived"
          @refresh="handleRefreshTable" />
      </template>
      
      <template #operation="{ row }">
        <t-space break-line>
          <view-contract-dialog :id="row.id" :order-id="row.orderId" :company-id="row.companyId"/>
          <!-- 查看订单 -->
          <view-order :id="row.orderId" />
          <update-remark-dialog :id="row.id" @request-success="handleDialogRequestSuccess"/>
          <update-pay-status-dialog :id="row.id" @request-success="handleDialogRequestSuccess"/>
        </t-space>
      </template>
    </custom-table>

  </t-card>
</template>

<script lang="ts">
export default {
  name: 'PayList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef } from 'vue';

import { payContractZhengCRUD } from '@/api/finance/pay';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import AmountReceivedDialog from './components/AmountReceivedDialog.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import UpdatePayStatusDialog from './components/UpdatePayStatusDialog.vue';
import UpdateRemarkDialog from './components/UpdateRemarkDialog.vue';
import EngineeringCostDiffDialog from './components/EngineeringCostDiffDialog.vue';
import ViewContractDialog from './components/ViewContractDialog.vue';
import ViewOrder from '@/pages/order/details/components/ViewOrder.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import { getUserListByRoleCode } from '@/api/system/user';
import listToTree from '@/utils/listToTree';
import disposableParams from '@/utils/disposableParams';
import { collectionConfigCRUD } from '@/api/config/common-config';
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = [{ id: null, name: '全部公司' }, ...data];
      defaultCompany.value = null
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetCompanyList();
// 精简部门列表
const simpleDeptList = ref([]);
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList().then((data) => {
    simpleDeptList.value = data;
    simpleDeptTree.value = listToTree(data);
  });
};
handleGetSimpleDeptTree();
// 设计师列表
const designerList = ref([]);
// 工程部经理
const engineeringManagerList = ref([]);
// 客服
const saleList = ref([]);

// 获取用户通过rolecode
const fetchUsersByRole = async (roleCode: string, targetList: Ref<any[], any[]>) => {
  try {
    const data = await getUserListByRoleCode({ roleCode });
    data.forEach((item:any) => {
      item.name = item.nickname
      item.parentId = item.deptId
    });
    targetList.value = data;
  } catch (error) {
    console.error(`Error fetching users with role ${roleCode}:`, error);
    targetList.value = []; // Reset on error
  }
};

// 初始化所有用户
const initializeUserLists = () => {
  fetchUsersByRole('designer', designerList);
  fetchUsersByRole('sloe', saleList);
  fetchUsersByRole('engineering_manager', engineeringManagerList);
};

// Call initialization
initializeUserLists();
// 3. 合并部门和用户数据，生成树形结构
const generateCombinedTree = (deptTree: any[], userList: any[], userType: string) => {
  // 创建用户按部门ID分组的映射
  const userMap = new Map<number, any[]>();
  userList.forEach(user => {
    if (!userMap.has(user.deptId)) {
      userMap.set(user.deptId, []);
    }
    userMap.get(user.deptId).push({
      ...user,
      isUser: true,
      userType: userType
    });
  });

  // 递归处理部门树
  const processTree = (nodes: any[]): any[] => {
    return nodes.map(node => {
      const newNode = { ...node };
      
      // 处理子部门
      if (newNode.children) {
        newNode.children = processTree(newNode.children);
      } else {
        newNode.children = [];
      }
      
      // 添加当前部门的用户
      if (userMap.has(newNode.id)) {
        newNode.children.push(...userMap.get(newNode.id));
      }
      
      // 保留有用户或有子部门的节点
      if (newNode.children.length > 0) {
        return newNode;
      }
      
      return null;
    }).filter(Boolean);
  };

  return processTree(deptTree);
};
// 4. 计算属性：生成各种组合树
const designerTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, designerList.value, 'designer');
});

const engineeringManagerTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, engineeringManagerList.value, 'engineering_manager');
});

const saleTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, saleList.value, 'sloe');
});
// 公司切换
const handleCompanyChange = () => {
  handleInitTable();
};
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
const table = ref([])
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  data.forEach((item: any) => {
    if(!item.amountOfMoney) {
      item.amountOfMoney=0
    }
    if(!item.contractPrice) {
      item.contractPrice=0
    }
    if(!item.engineeringCostDiff) {
      item.engineeringCostDiff=0
    }
    if(!item.amountReceived) {
      item.amountReceived=0
    }
    item.amountUnreceived = (item.amountOfMoney + item.engineeringCostDiff - item.amountReceived).toFixed(2)
  })
  console.log(data,'table');
  table.value =data
  return data;
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'engineeringStage', title: '施工阶段', fixed: 'left', width:90 },
  { colKey: 'customerName', title: '客户名称', fixed: 'left' , width:80},
  { colKey: 'propertyName', title: '楼盘地址', fixed: 'left', width: 160 },
  { colKey: 'saleId', title: '客服', width:80},
  { colKey: 'designerId', title: '设计师', width:80},
  { colKey: 'productDesignerId', title: '产品设计师', width:90},
  { colKey: 'engineeringManagerId', title: '工程部经理', width:90},
  { colKey: 'supervisionId', title: '监理', width:80},
  { colKey: 'contractPrice', title: '合同金额', width:110},
  { colKey: 'amountOfMoney', title: '应收金额', width:100},
  { colKey: 'engineeringCostDiff', title: '洽商金额'},
  { colKey: 'amountReceived', title: '实付金额', width:120},
  { colKey: 'amountUnreceived', title: '未收金额', width:120},
  { colKey: 'payStatus', title: '支付状态', width:80},
  { colKey: 'payNumber', title: '收款期数', width:80},
 
  { colKey: 'endTime', title: '催款时间', width:120},
  { colKey: 'contractSigningTime', title: '合同签订时间', width:120},

  
  { colKey: 'paymentStage', title: '收款阶段', width:120, ellipsis: true},
  { colKey: 'remark', title: '备注', width: 300, align:'left'},
  { colKey: 'operation', title: '操作', width: 180, fixed: 'right' },
];
const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
const handleSeachTable=(params:any) =>{

  disposableParams.set('to-do-tree-jump-params', {
    orderIds: '',
    stageType: '',
    payNumber: '',
  });
  if(params=='reset') {
    customSearchRef.value.params.payStatus = ''
  }
    const params1: Record<string, any> = { 
    
    ...customSearchRef.value.params, 
    companyId: defaultCompany.value,
  };
  customTableRef.value.initTable(params1);
  // handleInitTable()
  
}
// 处理初始化表格
const handleInitTable = () => {
  console.log(toDoTreeJumpParams,'toDoTreeJumpParams');
  collectionConfig.value = [
    {paymentStage:'收首期款', payNumber:1},
    {paymentStage:'收二期款', payNumber:2},
    {paymentStage:'收三期款', payNumber:3},
    {paymentStage:'收尾款', payNumber:3},
    {paymentStage:'确认首期款', payNumber:1},
    {paymentStage:'确认二期款', payNumber:2},
    {paymentStage:'确认尾款', payNumber:3},
    {paymentStage:'确认三期款', payNumber:3},
  ]
  // 待办树跳转参数

  const matchedConfig = ref()
  if(toDoTreeJumpParams?.stageType) {
    matchedConfig.value = collectionConfig.value.find(
      (item:any) => item.paymentStage === toDoTreeJumpParams.stageType
    );
  }
  const params: Record<string, any> = { 
    orderIds: toDoTreeJumpParams.orderIds,
    payName: toDoTreeJumpParams.stageType,
    payNumber: matchedConfig.value?.payNumber,
    ...customSearchRef.value.params, 
    companyId: defaultCompany.value,
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable()
});
onUpdated(() => {
  handleRefreshTable();
})
const collectionConfig = ref()
const handleGetCollectionConfig = async () => {
  const params = {
    pageSize:-1
  }
  const data = await collectionConfigCRUD.page(params)
  collectionConfig.value=data.list
  handleInitTable(); 
}
const defaultStatus = computed(() => {
  if (!toDoTreeJumpParams.orderIds) {
    return '0';
  }
  return '';
});
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 计算汇总值
const calculateSummary = (colKey: string) => {
  return table.value.reduce((sum, row) => sum + (parseFloat(row[colKey]) || 0), 0).toFixed(2);
};
// 普通表尾数据
const footData = computed(() => {
  return [
    {
      engineeringStage: '汇总',
      contractPrice: calculateSummary('contractPrice'),
      amountOfMoney: calculateSummary('amountOfMoney'),
      engineeringCostDiff: calculateSummary('engineeringCostDiff'),
      amountReceived: calculateSummary('amountReceived'),
      amountUnreceived: calculateSummary('amountUnreceived'),
    },
  ];
});
</script>

<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}

:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
</style>
